/*
 * Created on Oct 10, 2004
 */
package cnm.validator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Performs DTD validation on supplied XML document
 */
public class XmlDTDValidator
{

	public static void main(String[] args)
	{
		try
		{
			XmlDTDValidator parser = new XmlDTDValidator();
			parser.doParse(new File("./metadata/testdata/object.xml"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
	}

	/**
	 * Does DTD-based validation on File
	 */
	public void doParse(File xmlFilePath) throws RuntimeException
	{

		InputSource inputSource = null;
		try
		{
			inputSource = new InputSource(new FileReader(xmlFilePath));
		}
		catch (FileNotFoundException e)
		{
			throw new RuntimeException(e);
		}
		doParse(inputSource);

	}

	/**
	 * Does DTD-based validation on text
	 */
	public void doParse(String xmlText) throws RuntimeException
	{

		InputSource inputSource = new InputSource(new StringReader(xmlText));
		doParse(inputSource);

	}

	/**
	 * Does DTD-based validation on inputSource
	 */
	public void doParse(InputSource inputSource) throws RuntimeException
	{

		try
		{
			SAXReader reader = new SAXReader();
            reader.setValidation(false);
            //reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",true);
            
            XMLErrorHandler errorHandler = new XMLErrorHandler();
            reader.setErrorHandler(errorHandler);
            
            reader.setEntityResolver(new EntityResolver() {
                public InputSource resolveEntity(String publicId,
                        String systemId) throws SAXException, IOException {
                    return new InputSource("./metadata/testdata/object.dtd");
                }
            });
            
			reader.read(inputSource);
            
            XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
            if (errorHandler.getErrors().hasContent()) {
                    writer.write(errorHandler.getErrors());
            } else {
                    System.out.println("validate success.");
            }
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}

